import { Button, message, Modal, Table } from 'antd';
import Search from 'antd/lib/input/Search';
import { ColumnsType } from 'antd/lib/table';
import { checkPermission } from 'permission/Index';
import React from 'react';
import { RoleInfo } from '../../../schema/Role';
import { delRole, getRoleList } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { RoleOperation } from './component/RoleOperation';
import { JSONObject } from '../../../../seats/schema/common';

interface RoleState {
  roleName: string;
  tableData: RoleInfo[];
  resetPwdVisible: boolean;
  currentRecord: RoleInfo;
  pageInfo: {
    pageNum: number;
    pageSize: number;
    pageTotal: number;
  };
  tableLoading: boolean;
}

export default class Role extends React.Component<{}, RoleState> {
  columns: ColumnsType<RoleInfo>;

  roleOperationRef: React.RefObject<RoleOperation>;

  constructor(props: {}) {
    super(props);
    this.roleOperationRef = React.createRef();
    this.state = {
      roleName: '',
      tableData: [],
      resetPwdVisible: false,
      currentRecord: {} as RoleInfo,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };
    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '角色名',
        dataIndex: 'roleName',
        key: 'roleName',
        width: 300,
      },
      {
        title: '角色描述',
        dataIndex: 'roleDesc',
        key: 'roleDesc',
        ellipsis: true,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 240,
        render: (text, record, index) => {
          return (
            <>
              {checkPermission('/account/role/modify') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.modify(record);
                  }}
                >
                  编辑
                </Button>
              )}
              {checkPermission('/account/role/permission/save') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.setPermission(record);
                  }}
                >
                  功能权限
                </Button>
              )}
              {checkPermission('/account/role/delete') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.deleteRecord(record);
                  }}
                >
                  删除
                </Button>
              )}
            </>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.fetchList();
  }

  private modify(record: RoleInfo) {
    this.roleOperationRef.current?.open('modify', record);
  }

  /**
   * 跳转到角色功能权限页
   */
  private setPermission(record: RoleInfo) {
    const route = (this.props as JSONObject).history;
    route.push(`/webapp/account/role/permission?roleId=${record.roleId}`);
  }
  /**
   * 删除数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 删除角色
   */
  private deleteRecord(record: RoleInfo) {
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        delRole(record.roleId as number)
          .then(res => {
            message.success('删除成功');
            this.deleteFresh(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 查询角色
   */
  private search(value: string) {
    const pageInfo = this.state.pageInfo;
    pageInfo.pageNum = 1;
    this.setState(
      {
        roleName: value.trim(),
        pageInfo: pageInfo,
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  /**
   * 获取角色列表
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo } = this.state;
    const { pageNum, pageSize } = pageInfo;
    getRoleList(
      clearNull({
        roleName: this.state.roleName,
        pageSize: pageSize,
        pageNo: pageNum,
      })
    )
      .then(res => {
        this.setState({
          tableLoading: false,
        });
        const { count, data } = res;
        pageInfo.pageTotal = count || 0;
        this.setState({
          tableData: data || [],
          pageInfo: pageInfo,
        });
      })
      .catch(error => {
        this.setState({
          tableLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**
   * 表格行操作后，重置列表
   */
  private resetList() {
    this.jumpPage(1);
  }
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;
    const { columns, roleOperationRef } = this;
    return (
      <>
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Search
              className="mgr-header-search"
              placeholder="请输入角色名"
              enterButton="搜索"
              onSearch={value => this.search(value)}
            />
          </div>
          <div className="mgr-header-right">
            {checkPermission('/account/role/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.roleOperationRef.current?.open('create');
                }}
              >
                新建角色
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            scroll={{ x: '100%' }}
            columns={columns}
            dataSource={tableData}
            rowKey={record => record.roleName}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <RoleOperation
          ref={roleOperationRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
      </>
    );
  }
}
